/*
 * @Descripttion: 监听键盘上某个按键是否被按下
 * @Author: armin
 * @Date: 2022-04-11 11:22:01
 * @LastEditors: armin
 * @LastEditTime: 2022-04-11 11:26:14
 */

import { onMounted, onUnmounted, ref } from 'vue'

const useKeyPress = (targetKeyCode: string) => {
  const keyPressed = ref(false)

  const keyDownHandler = (e: KeyboardEvent) => {
    if (e.key === targetKeyCode) {
      keyPressed.value = true
    }
  }

  const keyUpHandler = (e: KeyboardEvent) => {
    if (e.key === targetKeyCode) {
      keyPressed.value = false
    }
  }
  onMounted(() => {
    document.addEventListener('keydown', keyDownHandler)
    document.addEventListener('keyup', keyUpHandler)
  })
  onUnmounted(() => {
    document.removeEventListener('keydown', keyDownHandler)
    document.removeEventListener('keyup', keyUpHandler)
  })
  return keyPressed
}

export default useKeyPress
